package kvraft

import (
	`fmt`
	`log`
	`sync/atomic`
	`time`
)

const IsDebugMode = false
const IsTimerMode = false
const IsOnly = false

func DPrintf(format string, a ...interface{}) (n int, err error) {
	if IsDebugMode {
		log.Printf(format, a...)
	}
	return
}

func TPrintf(format string, a ...interface{}) (n int, err error) {
	if IsTimerMode {
		log.Printf(format, a...)
	}
	return
}

func FPrintf(format string, a ...interface{}) (n int, err error) {
	if IsOnly {
		log.Printf(format, a...)
	}
	return
}

type HeartBeatHelper struct {
	nextTimeOut int64
}

// 将nextTimeOut更新到now + HeartBeatTimeOut，返回这个时间
func (tm *HeartBeatHelper) updateTimeOut() (t time.Duration) {
	t = Now() + time.Second
	atomic.StoreInt64(&tm.nextTimeOut, int64(t))
	return
}

// 将nextTimeOut更新到now + HeartBeatTimeOut，返回这个时间
func (tm *HeartBeatHelper) getNextTimeOut() time.Duration {
	return time.Duration(atomic.LoadInt64(&tm.nextTimeOut))
}

func (tm *HeartBeatHelper) SleepUntilNextTimeOut() {
	time.Sleep(tm.getNextTimeOut() - Now())
}

var to = HeartBeatHelper{}

func init() {
	go waitHeartBeatTimeOut()
}
func waitHeartBeatTimeOut() {
	to.updateTimeOut()
	for true {
		to.SleepUntilNextTimeOut()
		if Now() >= to.getNextTimeOut() { // follower超时了，这里不可能是candidate
			//if identity == Candidate || (identity == Follower && isTimeOut) { // follower超时了，这里不可能是candidate
			fmt.Println("****************************************************")
			to.updateTimeOut()
			return
		}
	}
}
